# 打印检查结果
printResult() {
        if [[ $1 == "ok" ]]; then
                printf "\033[32m%-9s %-50s\033[0m%s\n" "[OK]" "$2" "$3"
        elif [[ $1 == "error" ]]; then
                printf "\033[31m%-9s %-50s\033[0m%s\n" "[ERROR]" "$2" "$3"
        elif [[ $1 == "warning" ]]; then
                printf "\033[33m%-9s %-50s\033[0m%s\n" "[WARNING]" "$2" "$3"
        fi
}

# 打印检查项
printCheckItem() {
	for i in {1..92}; do
		printf "\033[33m=\033[0m"
	done
	printf "\033[33m=\033[0m\n"
	if [[ $# -eq 1 ]]; then
		printf "\033[33m%-37s%s\033[0m\n" " " "$1"
		for i in {1..92}; do
			printf "\033[33m=\033[0m"
		done
		printf "\033[33m=\033[0m\n"
	fi
}

# 打印检查结果
printUsage() {
        name_usage=$1
        max_usage=$(echo $2 | awk '{print int($0)+1}')
        echo "$name_usage:" " $2"
       
}

# 获取下一交易日日期
getNextTradeDate() {
        case $today_week in
        0 | 1 | 2 | 3 | 4)
                next_trade_date=$(date -d +1day +%Y%m%d)
                ;;
        5)
                next_trade_date=$(date -d +3day +%Y%m%d)
                ;;
        6)
                next_trade_date=$(date -d +2day +%Y%m%d)
                ;;
        esac
        printf $next_trade_date
}

# 判断当前所属交易日
checkTradeDate() {
        if [[ $now_time_hour > 18 ]]; then
                printf $(getNextTradeDate)
        else
                printf $(date -d now +%Y%m%d)
        fi
}


#获取并计算CPU、内存、硬盘使用率
calUsage() {
        TOTAL_MEM=$(free | awk '{if(NR==2) print $2}')
        USED_MEM=$(free | awk '{if(NR==2) print $3}')
        MEM_USAGE=$(awk -v m1=$USED_MEM -v m2=$TOTAL_MEM 'BEGIN{printf "%.2f", m1*100/m2}')
        DISK_USAGE=$(df -h | awk '{if($6=="/") print $5}' | sed -r 's/([0-9]*)%/\1/')
        DISK_HOME_USAGE=$(df -h | awk '{if($6=="/home") print $5}' | sed -r 's/([0-9]*)%/\1/')
        #CPU时间计算公式：CPU_TIME=user+system+nice+idle+iowait+irq+softirq
        #CPU使用率计算公式：cpu_usage=(idle2-idle1)/(cpu2-cpu1)*100
        #默认时间间隔
        TIME_INTERVAL=0.2
        LAST_CPU_INFO=$(cat /proc/stat | grep -w cpu | awk '{print $2,$3,$4,$5,$6,$7,$8}')
        LAST_SYS_IDLE=$(echo $LAST_CPU_INFO | awk '{print $4}')
        LAST_TOTAL_CPU_T=$(echo $LAST_CPU_INFO | awk '{print $1+$2+$3+$4+$5+$6+$7}')
        sleep ${TIME_INTERVAL}
        NEXT_CPU_INFO=$(cat /proc/stat | grep -w cpu | awk '{print $2,$3,$4,$5,$6,$7,$8}')
        NEXT_SYS_IDLE=$(echo $NEXT_CPU_INFO | awk '{print $4}')
        NEXT_TOTAL_CPU_T=$(echo $NEXT_CPU_INFO | awk '{print $1+$2+$3+$4+$5+$6+$7}')
        #系统空闲时间
        SYSTEM_IDLE=$(echo ${NEXT_SYS_IDLE} ${LAST_SYS_IDLE} | awk '{print $1-$2}')
        #CPU总时间
        TOTAL_TIME=$(echo ${NEXT_TOTAL_CPU_T} ${LAST_TOTAL_CPU_T} | awk '{print $1-$2}')
        CPU_USAGE=$(echo ${SYSTEM_IDLE} ${TOTAL_TIME} | awk '{printf "%.2f", 100-$1/$2*100}')
}

# 检查项
itemCalUsage() {
	calUsage
	printUsage "CPU usage" $CPU_USAGE
	printUsage "MEM usage" $MEM_USAGE
	printUsage "Disk / usage" $DISK_USAGE
	if [[ $(df -h | grep "/home") ]]; then
		printUsage "Disk /home usage" $DISK_HOME_USAGE
	fi
}

# 检查行情日志是否有行情信息
checkMarketData() {
	#checkFilePath "/app/cts_test/logs/logs_" "market"
	checkFilePath $market_part_path "market"
	# 确认日志目录及文件都存在再检查
	if [[ $file_exist -eq 1 ]]; then
		# 当前交易日日期
		trade_date=$(checkTradeDate)
		# 行情日志最新的行情信息
		time_market_data=$(cat $logs_path/$lastest_file | grep 'RecvMarketData\|Receive market data' | tail -n 1 | sed -r 's/.*[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9] ([0-9][0-9]):[0-9][0-9]:.*/\1/')
		#time_market_data=$(cat  $logs_path/$lastest_file | grep 'RecvMarketData\|Receive market data'  | tail -n 1 |sed -r 's/.* \[([0-9][0-9]):[0-9][0-9]:[0-9][0-9].*/\1/')
		#	receive_market_data=$(grep "Receive market data, Instrument:.* TradingDay: $trade_date" $logs_path/$lastest_file | tail -n 1)
		#echo $time_market_data
		#echo $now_time_hour
		#if [[ -n $receive_market_data ]]; then
		if [[ $time_market_data == $now_time_hour ]]; then
			printResult "ok" "进程：$monitor_process 状态正常。" "> $lastest_file"
		else
			printResult "error" "进程：$monitor_process 状态异常！" "> $lastest_file"
		fi
	fi
}

# 检查日志文件是否有报错信息
checkLogsError() {
	monitor_process=$1
	checkFilePath $cts_part_path $monitor_process
	# 进程日志报错信息
	# 确认日志目录及文件都存在再检查
	if [[ $file_exist -eq 1 ]]; then
		#从最近一次启动日志开始检查
		log_init_line=$(sed -n '/Initialize/=' $logs_path/$lastest_file | tail -n 1)
		if [[ $log_init_line == '' ]]; then
			log_init_line=1
		fi
		error_report=$(tail -n +$log_init_line $logs_path/$lastest_file | grep ERROR_REPORT)
		if [[ -z $error_report ]]; then
			printResult "ok" "Log: $monitor_process 状态正常。" "> $lastest_file"
		else
			printResult "error" "Log: $monitor_process 状态异常！" "> $lastest_file"
		fi
	fi
}

# 检查进程
checkProcess() {
	monitor_process=$1
	res=$(ps -ef | grep $monitor_process | grep -v grep)
	if [[ -n $res ]]; then
		printf ''
		#printResult "ok" "Process: $monitor_process is normal."
	else
		printResult "error" "Process: $monitor_process is down!"
	fi
}

# 检查行情是否初始化完成
#checkInitStatus() {
#
#}

###########################选择巡检项目###########################

#source $home_path/list_check.conf
#source $home_path/function_app.sh

CUR_TIME=$(date "+%Y-%m-%d %H:%M:%S")
main() {
    # checkAppStatus
    echo [RUN TIME: $CUR_TIME]
    itemCalUsage
    #showAllApp
}


main
